import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { 
  authApi, 
  productApi, 
  caseApi, 
  statsApi
} from './api';
import type { Product, Case, User } from '../types';

// 认证状态管理
interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  loading: boolean;
  login: (username: string, password: string, remember?: boolean) => Promise<void>;
  logout: () => void;
  checkAuth: () => Promise<void>;
}

export const useAuthStore = create<AuthState>()(persist((set) => ({
  user: null,
  token: null,
  isAuthenticated: false,
  loading: false,
  
  login: async (username, password, remember = false) => {
    set({ loading: true });
    try {
      const response = await authApi.login({ username, password, remember });
      const { token, user: loginUser } = response;
      localStorage.setItem('auth_token', token);
      // 转换登录响应的用户数据为完整的User类型
      const user: User = {
        id: loginUser.id,
        username: loginUser.username,
        nickname: loginUser.username, // 使用username作为nickname
        role: loginUser.role as 'admin' | 'guest',
        status: 'active' as const,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };
      set({ user, token, isAuthenticated: true, loading: false });
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  },
  
  logout: async () => {
    try {
      await authApi.logout();
    } catch (error) {
      console.error('Logout error:', error);
    } finally {
      localStorage.removeItem('auth_token');
      set({ user: null, token: null, isAuthenticated: false });
    }
  },
  
  checkAuth: async () => {
    const token = localStorage.getItem('auth_token');
    if (!token) {
      set({ token: null, isAuthenticated: false, loading: false });
      return;
    }
    
    set({ loading: true });
    try {
      const user = await authApi.getProfile();
      set({ user, token, isAuthenticated: true, loading: false });
    } catch {
      localStorage.removeItem('auth_token');
      set({ user: null, token: null, isAuthenticated: false, loading: false });
    }
  },
}), {
  name: 'auth-storage',
  partialize: (state) => ({ 
    isAuthenticated: state.isAuthenticated,
    user: state.user,
    token: state.token
  })
}));

// 产品状态管理
interface ProductState {
  products: Product[];
  currentProduct: Product | null;
  loading: boolean;
  total: number;
  fetchProducts: (params?: {
    page?: number;
    pageSize?: number;
    keyword?: string;
    categoryId?: string;
    status?: string;
    material?: string;
    priceRange?: string;
  }) => Promise<void>;
  fetchProduct: (id: string) => Promise<void>;
  createProduct: (product: Omit<Product, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>;
  updateProduct: (id: string, product: Partial<Product>) => Promise<void>;
  deleteProduct: (id: string) => Promise<void>;
}

export const useProductStore = create<ProductState>((set, get) => ({
  products: [],
  currentProduct: null,
  loading: false,
  total: 0,
  
  fetchProducts: async (params = {}) => {
    set({ loading: true });
    try {
      const response = await productApi.getProducts(params);
      set({ 
        products: response.products, 
        total: response.total,
        loading: false 
      });
      // 只有在管理页面才显示成功提示，避免在前台页面显示
      if (window.location.pathname.includes('/admin')) {
        const { message } = await import('antd');
        message.success(`成功加载 ${response.products.length} 个产品`);
      }
    } catch (error) {
      set({ loading: false });
      console.error('获取产品列表失败:', error);
    }
  },
  
  fetchProduct: async (id: string) => {
    set({ loading: true });
    try {
      const response = await productApi.getProduct(id);
      set({ currentProduct: response, loading: false });
    } catch (error) {
      set({ loading: false });
      console.error('获取产品详情失败:', error);
    }
  },
  
  createProduct: async (product) => {
    set({ loading: true });
    try {
      const response = await productApi.createProduct(product);
      const { products } = get();
      set({ 
        products: [response, ...products],
        loading: false 
      });
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  },
  
  updateProduct: async (id: string, product) => {
    set({ loading: true });
    try {
      const response = await productApi.updateProduct(id, product);
      const { products } = get();
      set({ 
        products: products.map(p => p.id === id ? response : p),
        loading: false 
      });
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  },
  
  deleteProduct: async (id: string) => {
    set({ loading: true });
    try {
      await productApi.deleteProduct(id);
      const { products } = get();
      set({ 
        products: products.filter(p => p.id !== id),
        loading: false 
      });
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  }
}));

// 案例状态管理
interface CaseState {
  cases: Case[];
  currentCase: Case | null;
  loading: boolean;
  total: number;
  fetchCases: (params?: {
    page?: number;
    pageSize?: number;
    keyword?: string;
    industryId?: string;
    status?: string;
  }) => Promise<void>;
  fetchCase: (id: string) => Promise<void>;
  createCase: (caseData: Omit<Case, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>;
  updateCase: (id: string, caseData: Partial<Case>) => Promise<void>;
  deleteCase: (id: string) => Promise<void>;
}

export const useCaseStore = create<CaseState>((set, get) => ({
  cases: [],
  currentCase: null,
  loading: false,
  total: 0,
  
  fetchCases: async (params = {}) => {
    set({ loading: true });
    try {
      const response = await caseApi.getCases(params);
      set({ 
        cases: response.cases, 
        total: response.total,
        loading: false 
      });
      // 只有在管理页面才显示成功提示，避免在前台页面显示
      if (window.location.pathname.includes('/admin')) {
        const { message } = await import('antd');
        message.success(`成功加载 ${response.cases.length} 个案例`);
      }
    } catch (error) {
      set({ loading: false });
      console.error('获取案例列表失败:', error);
    }
  },
  
  fetchCase: async (id: string) => {
    set({ loading: true });
    try {
      const response = await caseApi.getCase(id);
      set({ currentCase: response, loading: false });
    } catch (error) {
      set({ loading: false });
      console.error('获取案例详情失败:', error);
    }
  },
  
  createCase: async (caseData) => {
    set({ loading: true });
    try {
      const response = await caseApi.createCase(caseData);
      const { cases } = get();
      set({ 
        cases: [response, ...cases],
        loading: false 
      });
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  },
  
  updateCase: async (id: string, caseData) => {
    set({ loading: true });
    try {
      const response = await caseApi.updateCase(id, caseData);
      const { cases } = get();
      set({ 
        cases: cases.map(c => c.id === id ? response : c),
        loading: false 
      });
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  },
  
  deleteCase: async (id: string) => {
    set({ loading: true });
    try {
      await caseApi.deleteCase(id);
      const { cases } = get();
      set({ 
        cases: cases.filter(c => c.id !== id),
        loading: false 
      });
    } catch (error) {
      set({ loading: false });
      throw error;
    }
  }
}));



// 网站设置状态管理已移除 - 不再需要网站设置功能

// 统计数据状态
interface StatsState {
  stats: {
    totalProducts: number;
    totalCases: number;
    totalViews: number;
    totalUsers: number;
  } | null;
  loading: boolean;
  fetchStats: () => Promise<void>;
}

export const useStatsStore = create<StatsState>((set) => ({
  stats: null,
  loading: false,
  
  fetchStats: async () => {
    set({ loading: true });
    try {
      const stats = await statsApi.getDashboardStats();
      set({ 
        stats: {
          totalProducts: stats.totalProducts,
          totalCases: stats.totalCases,
          totalViews: 0, // 暂时设为0，等后端提供
          totalUsers: 0  // 暂时设为0，等后端提供
        }, 
        loading: false 
      });
    } catch (error) {
      set({ loading: false });
      console.error('获取统计数据失败:', error);
    }
  },
}));

// 全局UI状态
interface UIState {
  theme: 'light' | 'dark';
  sidebarCollapsed: boolean;
  loading: boolean;
  setTheme: (theme: 'light' | 'dark') => void;
  setSidebarCollapsed: (collapsed: boolean) => void;
  setLoading: (loading: boolean) => void;
}

export const useUIStore = create<UIState>()(persist((set) => ({
  theme: (localStorage.getItem('theme') as 'light' | 'dark') || 'light',
  sidebarCollapsed: localStorage.getItem('sidebarCollapsed') === 'true',
  loading: false,
  
  setTheme: (theme) => {
    set({ theme });
    localStorage.setItem('theme', theme);
    document.documentElement.setAttribute('data-theme', theme);
  },
  
  setSidebarCollapsed: (collapsed) => {
    set({ sidebarCollapsed: collapsed });
    localStorage.setItem('sidebarCollapsed', String(collapsed));
  },
  
  setLoading: (loading) => {
    set({ loading });
  },
}), {
  name: 'ui-storage',
  partialize: (state) => ({
    theme: state.theme,
    sidebarCollapsed: state.sidebarCollapsed
  })
}));